<?php
namespace app\zhonghang\controller;
use think\Controller;
use think\Db;
use think\Cache;
date_default_timezone_set('Asia/Shanghai');
class Trade extends Base {
    //空操作
    public function _initialize(){
        parent::_initialize();
    }
    public function _empty(){
        header("HTTP/1.0 404 Not Found");
        $this->display('Public:404');
    }
    //查询配置
    public function configs(){
    	$list = Db::name('App_config')->select();
    	foreach($list as $key=>$value){
    		$list[$value['key']] = $value['value'];
    	}
    	return $list;
    }
    public function panduanTime(){
    	$checkDayStr = date('Y-m-d ',time());
    	$config = $this->configs();
    	$timeBegin1 = strtotime($checkDayStr.$config['trade_star'].":00");
    	$timeEnd1 = strtotime($checkDayStr.$config['trade_end'].":00");
    	$curr_time = time();
//     	dump($checkDayStr.$config['trade_star'].":00");
//     	dump($checkDayStr.$config['trade_end'].":00");
//     	dump($curr_time);
//     	dump($timeBegin1);
//     	dump($timeEnd1);
    	if($curr_time >= $timeBegin1 && $curr_time <= $timeEnd1)
    	{
    		return true;
    	}
    	
    	return false;
    }
    public function week(){
    	if((date('w') == 6) || (date('w') == 0)){
    		//        		echo '今天是周末';
    		return false;
    	}else{
    		// 		    echo '当然就不是周末了';
    		return true;
    	}
    }
    /**
     * 股票购买方法
     */
    public function buyOrders(){
    	$week = $this->week();
    	if(!$week){
    		$data['info'] = '当前时间无法交易';
    		$data['status'] = -11;
    		return json($data);
    	}
    	
    	$member = $this->member;
    	$member_id = $member['member_id'];
    	$num = input('num');
    	$payPwd = input('payPwd');
    	$user = Db::name('Users')->where(array('userId'=>$member['member_id']))->find();
//     	if($user['payPwd'] != md5($payPwd)){
//     		$data['info'] = '二级密码不正确';
//     		$data['status'] = -2;
//     		return json($data);
//     	}
		
		$time_res = $this->panduanTime();
    	if(!$time_res){
    		$data['info'] = '当前时间无法交易';
    		$data['status'] = -11;
    		return json($data);
    	}
    	//判断是否完善银行信息
    	if(empty($member['kaihuhang']) || empty($member['bank_card']) || empty($member['kaihuren']) || empty($member['bank_address']) || empty($member['zhifubao'])){
    		$data['info'] = '请完银行信息之后即可购买';
    		$data['status'] = -1;
    		return json($data);
    	}
    	//判断买入数量
    	if(is_int($num)){
    		$data['status']=-3;
    		$data['info']='数量有误';
    		return json($data);
    	}
    	$config = $this->configs();
    	$min = $config['min_num'];
    	$max = $config['max_num'];
    	if($num <= 0){
    		$data['status']=-4;
    		$data['info']='挂单数量有误';
    		return json($data);
    	}
    	//数量小于零
    	if($num < $min){
    		$data['status']=-4;
    		$data['info']='挂单数量不能低于'.$min;
    		return json($data);
    	}
    	if($num > $max){
    		$data['status']=-4;
    		$data['info']='挂单数量不能高于'.$max;
    		return json($data);
    	}
    	$price = $config['price'];
    	
    	
    	$arr['member_id'] = $member_id;
    	$arr['type'] = 'buy';
    	$arr['price'] =  $price;
    	$arr['num'] = $num;
    	$arr['add_time'] = time();
    	$arr['status'] = 0;
    	$res = Db::name('Orders')->insert($arr);
    	if($res){
    		$data['info'] = '成功';
    		$data['status'] = 1;
    		return json($data);
    	}else{
			$data['info'] = '网络异常';
			$data['status'] = -2;
			return json($data);
		}
    }
    /**
     * 挂卖
     */
    public function sellOrders(){
    	$member = $this->member;
    	$member_id = $member['member_id'];
    	$num = I('num');
    	$payPwd = I('payPwd');
    	$user = Db::name('Users')->where(array('userId'=>$member['member_id']))->find();
//     	if($user['payPwd'] != md5($payPwd)){
//     		$data['info'] = '二级密码不正确';
//     		$data['status'] = -2;
//     		return json($data);
//     	}
    	$week = $this->week();
    	if(!$week){
    		$data['info'] = '当前时间无法交易';
    		$data['status'] = -11;
    		return json($data);
    	}
    	$time_res = $this->panduanTime();
    	if(!$time_res){
    		$data['info'] = '当前时间无法交易';
    		$data['status'] = -11;
    		return json($data);
    	}
    	//防止重复提交
    	$trade = Cache::get('tradeMoney_'.$member['member_id']);
    	if($trade == true){
    		$msg['status'] = -2;
    		$msg['info'] = "请勿频繁操作";
    		return json($msg);exit;
    	}
    	//设置缓存
    	Cache::set('tradeMoney_'.$member['member_id'],true,5);
    	
    	//判断是否完善银行信息
    	if(empty($member['kaihuhang']) || empty($member['bank_card']) || empty($member['kaihuren']) || empty($member['bank_address']) || empty($member['zhifubao'])){
    		$data['info'] = '请完银行信息之后即可出售';
    		$data['status'] = -1;
    		return json($data);
    	}
    	//判断买入数量
    	if(is_int($num)){
    		$data['status']=-3;
    		$data['info']='数量有误';
    		return json($data);
    	}
    	if($num <= 0){
    		$data['status']=-4;
    		$data['info']='挂单数量有误';
    		return json($data);
    	}
    	//判断账户余额
    	$member_account = Db::name('App_member_account')->where(array('member_id'=>$member['member_id']))->find();
    	if($member_account['account_type_3'] < $num){
    		$data['info'] = '账户余额不足';
    		$data['status'] = -3;
    		return json($data);
    	}
    	$config = $this->configs();
    	$min = $config['min_num'];
    	$max = $config['max_num'];
    	//数量小于零
    	if($num < $min){
    		$data['status']=-4;
    		$data['info']='挂单数量不能低于'.$min;
    		return json($data);
    	}
    	if($num > $max){
    		$data['status']=-4;
    		$data['info']='挂单数量不能高于'.$max;
    		return json($data);
    	}
		//扣钱
    	$res[] = Db::name('App_member_account')->where(array('member_id'=>$member['member_id']))->setDec('account_type_3',$num);
    	$fee = $num * $config['trade_fee'] * 0.01;
   		$after_fee_num = $num - $fee;
    	$price = $config['price'];
    	$arr['member_id'] = $member_id;
    	$arr['type'] = 'sell';
    	$arr['price'] =  $price;
    	$arr['num'] = $after_fee_num;
    	$arr['fee'] = $fee;
    	$arr['add_time'] = time();
    	$arr['status'] = 0;
    	$res = Db::name('Orders')->insert($arr);
    	if($res){
    		$data['info'] = '成功';
    		$data['status'] = 1;
    		return json($data);
    	}else{
    		$data['info'] = '网络异常';
    		$data['status'] = -2;
    		return json($data);
    	}
    }
    /**
     * 挂卖挂买记录
     */
    public function getBuySellList(){
    	$member = $this->member;
    	$type = input('type');
    	$id = input('id');
    	if($type == 1){
    		$where['type'] = 'buy';
    	}else{
    		$where['type'] = 'sell';
    	}
    	if($id){
    		$where['id'] = array('gt',$id);
    	}
    	$where['status'] = 0;
    	$where['member_id'] = array('neq',$member['member_id']);
    	$list = Db::name('Orders')->where($where)->order('add_time desc')->select();
    	foreach($list as $k=>$v){
    		$list[$k]['all_money'] = $list[$k]['price'] * $list[$k]['num'];
    		$user = Db::name('Users')->where(array('userId'=>$list[$k]['member_id']))->find();
    		$list[$k]['loginName'] = $user['loginName'];
    	}
    	if(!empty($list)){
    		$data['list'] =$list;
    		$data['info'] = '成功';
    		$data['status'] = 1;
    		return json($data);	
    	}else{
    		$data['list'] = array();
    		$data['info'] = '暂无记录';
    		$data['status'] = -1;
    		return json($data);
    	}
    }
   	/**
   	 * 购买操作
   	 */
    public function buyAction(){
    	$member = $this->member;
    	$order_id = input('order_id');
    	$payPwd = input('payPwd');
    	$order = Db::name('Orders')->where(array('id'=>$order_id))->find();
    	if($order['status'] != 0){
    		$data['info'] = '订单状态已改变';
    		$data['status'] = -1;
    		return json($data);
    	}
    	$week = $this->week();
    	if(!$week){
    		$data['info'] = '当前时间无法交易';
    		$data['status'] = -11;
    		return json($data);
    	}
    	$time_res = $this->panduanTime();
    	if(!$time_res){
    		$data['info'] = '当前时间无法交易';
    		$data['status'] = -11;
    		return json($data);
    	}
    	$trade = Cache::get('tradeMoney_'.$member['member_id']);
    	if($trade == true){
    		$msg['status'] = -2;
    		$msg['info'] = "请勿频繁操作";
    		return json($msg);exit;
    	}
    	//设置缓存
    	Cache::set('tradeMoney_'.$member['member_id'],true,5);
    	
    	if($order['member_id'] == $member['member_id']){
    		$data['info'] = '无法购买自己的订单';
    		$data['status'] = -2;
    		return json($data);
    	}
    	$user = Db::name('Users')->where(array('userId'=>$member['member_id']))->find();
    	if($user['payPwd'] != md5($payPwd)){
    		$data['info'] = '二级密码不正确';
    		$data['status'] = -3;
    		return json($data);
    	}
    	//判断是否完善银行信息
    	if(empty($member['kaihuhang']) || empty($member['bank_card']) || empty($member['kaihuren']) || empty($member['bank_address']) || empty($member['zhifubao'])){
    		$data['info'] = '请完银行信息之后即可购买';
    		$data['status'] = -4;
    		return json($data);
    	}
    	//修改订单状态
    	$order_status['status'] = 1;
    	$res[] = Db::name('Orders')->where(array('id'=>$order_id))->update($order_status);
    	$config = $this->configs();
    	//加入交易表
    	$trade['sell_order_id'] = $order_id;
    	$trade['buy_member_id'] = $member['member_id'];
    	$trade['sell_member_id'] = $order['member_id'];
    	$trade['price'] = $order['price'];
    	$trade['num'] = $order['num'];
    	$trade['all_money'] = $order['price']*$order['num'];
    	$trade['fee'] = $order['num'] * $config['trade_fee'] * 0.01;
    	$trade['status'] = 0;
    	$trade['add_time'] = time();
    	$res[] = Db::name('Trade')->insert($trade);
    	if($res){
    		//发送短信TODO
    		$phone_res[] = $this->smsSendTrade($member['phone']);
    		$sell_member_relation = Db::name('App_member_relation')->where(array('member_id'=>$order['member_id']))->find();
    		$phone_res[] = $this->smsSendTrade($sell_member_relation['phone']);
    		
    		
    		$data['info'] = '确认成功请及时与卖家联系';
    		$data['status'] = 1;
    		return json($data);
    	}else{
    		$data['info'] = '系统繁忙';
    		$data['status'] = -6;
    		return json($data);
    	}
    }
    /**
     * 卖出操作
     */
    public function sellAction(){
    	$member = $this->member;
    	$order_id = input('order_id');
    	$payPwd = input('payPwd');
    	$order = Db::name('Orders')->where(array('id'=>$order_id))->find();
    	if($order['status'] != 0){
    		$data['info'] = '订单状态已改变';
    		$data['status'] = -1;
    		return json($data);
    	}
    	$week = $this->week();
    	if(!$week){
    		$data['info'] = '当前时间无法交易';
    		$data['status'] = -11;
    		return json($data);
    	}
    	$time_res = $this->panduanTime();
    	if(!$time_res){
    		$data['info'] = '当前时间无法交易';
    		$data['status'] = -11;
    		return json($data);
    	}
    	if($order['member_id'] == $member['member_id']){
    		$data['info'] = '无法购买自己的订单';
    		$data['status'] = -2;
    		return json($data);
    	}
    	$user = Db::name('Users')->where(array('userId'=>$member['member_id']))->find();
    	if($user['payPwd'] != md5($payPwd)){
    		$data['info'] = '二级密码不正确';
    		$data['status'] = -3;
    		return json($data);
    	}
    	//判断账户余额
    	$member_account = Db::name('App_member_account')->where(array('member_id'=>$member['member_id']))->find();
    	$config = $this->configs();
    	$fee = $order['num'] * $config['trade_fee'] * 0.01;
    	$all_num = $fee+ $order['num'];
    	
    	if($member_account['account_type_3'] < $all_num){
    		$data['info'] = '账户余额不足';
    		$data['status'] = -5;
    		return json($data);	
    	}
    	//判断是否完善银行信息
    	if(empty($member['kaihuhang']) || empty($member['bank_card']) || empty($member['kaihuren']) || empty($member['bank_address']) || empty($member['zhifubao'])){
    		$data['info'] = '请完银行信息之后即可购买';
    		$data['status'] = -4;
    		return json($data); 
    	}
    	//扣除自身钱包的钱TODO
    		
    	$res[] = Db::name('App_member_account')->where(array('member_id'=>$member['member_id']))->setDec('account_type_3',$all_num);
 		
    	//修改订单状态
    	$order_status['status'] = 1;
    	$res[] = Db::name('Orders')->where(array('id'=>$order_id))->update($order_status);
    	
    	//加入交易表
    	$trade['buy_order_id'] = $order_id;
    	$trade['buy_member_id'] = $order['member_id'];
    	$trade['sell_member_id'] = $member['member_id'];
    	$trade['price'] = $order['price'];
    	$trade['num'] = $order['num'];
    	$trade['all_money'] = $order['price']*$order['num'];
    	$trade['fee'] = $fee;
    	$trade['status'] = 0;
    	$trade['add_time'] = time();
    	$res[] = Db::name('Trade')->insert($trade);
    	if($res){
    		//发送短信
    		$phone_res[] = $this->smsSendTrade($member['phone']);
    		$buy_member_relation = Db::name('App_member_relation')->where(array('member_id'=>$order['member_id']))->find();
    		$phone_res[] = $this->smsSendTrade($buy_member_relation['phone']);
    		
    		$data['info'] = '确认成功请及时与买家联系';
    		$data['status'] = 1;
    		return json($data);
    	}else{
    		$data['info'] = '系统繁忙';
    		$data['status'] = -6;
    		return json($data);
    	}
    }
   	
   
    /**
     * 发送短信
     */
    public function smsSendTrade($phone){
    	$A_Sms = new \SmsApi();
    	$content = '尊敬的YHBB会员，您的订单已经匹配，请留意查看';
    	$res = $A_Sms->send($phone,$content);
    	return $res;
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    /**
     * 获得当前股票交易金额
     * @param unknown $now_num
     * @return number
     */
    public function getNowPrice($now_num){//200
    	$where['type'] = 'buy';
    	$ratio = M('Ratio')->where(array('status'=>0))->find();
    	$where['ratio_id'] = $ratio['id'];
  		//当前比例的数量
    	$num = $ratio['num'];
    	$ttt = $this->ratio();
    	if($ttt){
    		$price = $ttt;
    	}else{
    		$order = M('Orders')->where($where)->order('add_time desc')->find();
    		$price = $order['price'];
    	}
		$base = $this->config['vr_danwei'];
    	$bili = $this->config['vr_money'];
    	//取余
    	$r = fmod($num,$base); 
    	//没满足第一次涨价的股票量
    	$a = $base-$r;		
    	if($now_num>$a){		        
    		$f = $a;
    	}else{
    		$f = $now_num;		//1  
    	}
    	//满足涨价的股票量
    	$b = $now_num-$f;   	
    	//涨了几次价格 (取整)
    	$c = ceil($b/$base);  
    	$d = fmod($b,$base);  
    	for($i=0;$i<$c+1;$i++){
    		if($i == 0){
    			$arr[$i]['num'] = $f;
    				//判断是否涨价
    				if($r == 0){
    					if($num !=0){
    						$now_bili = $bili;
    					}else{
    						$now_bili = $i*$bili;
    					}
    				}else{
    					$now_bili = $i*$bili;
    				}
    		}else{
    			if($i == $c){
    				if($d == 0){
    					//整除的
    					$arr[$i]['num'] = $base;
    				}else{
    					$arr[$i]['num'] = $d;
    				}
    				
    			}else{
    				$arr[$i]['num'] = $base;
    			}
    			$now_bili =	($i+1)*$bili;
    		}
    		$arr[$i]['money'] = $price+$now_bili;
    		$arr[$i]['all_money'] = $arr[$i]['money']*$arr[$i]['num'];
    	}
    	return $arr;
    }
    
    public function ratio(){
    	//查看股票进程表
    	$ratio = M('Ratio')->where(array('status'=>0))->find();
    	if($ratio){
    		if($ratio['num'] == 0){
    			$price = $ratio['first_price'];
    		}else{
    			return false;
    		}
    	}	
//     	echo '111111111111';
//     	dump($price);
    	return $price;
    }
    
    
    
    
    
  
	
   
    /**
     * 获得当前的st价格
     */
    public function getNowStPrice(){
    	$st_up_num  = $this->config['st_up_num'];
    	$st_up_bili = $this->config['st_up_bili'];
    	$all_money = M('Trade')->sum('num');
    	$num = floor($all_money/$st_up_num);
    	$money= $num*$st_up_bili;
    	$first_order = M('Orders')->where(array('order_id'=>1))->find();
    	$now_price = $first_order['price']+$money;
    	return $now_price; 
    }
    /**
     * 为用户加钱
     * @param 用户id $member_id
     * @param 金额   $money
     * @param 类型   $type rmb forzen
     * @return unknown
     */
    public function addMoney($member_id,$money,$type){
    	$res = M('Member_account')->where(array('member_id'=>$member_id))->setInc($type,$money);
    	return $res;
    }
    /**
     * 为用户减钱
     * @param 用户id $member_id
     * @param 金额   $money
     * @param 类型   $type
     * @return unknown
     */
    public function subMoney($member_id,$money,$type){
    	$res = M('Member_account')->where(array('member_id'=>$member_id))->setDec($type,$money);
    	return $res;
    }
   
    /**
     *
     * @param 买入用户id  $buy_member
     * @param 卖出用户id  $sell_member
     * @param 商品id     $goods_id
     * @param 数量                     $num
     * @param 金额                     $price
     * @param 买入订单id  $order_buy_id
     * @param 卖出订单id  $order_sell_id
     * @return unknown
     */
    public function addTrade($buy_member,$sell_member,$goods_id,$num,$price,$order_buy_id,$order_sell_id){
    	$data['buy_member'] = $buy_member;
    	$data['sell_member'] = $sell_member;
    	$data['goods_id'] = $goods_id;
    	$data['num'] = $num;
    	$data['price'] = $price;
    	$data['order_buy_id'] = $order_buy_id;
    	$data['order_sell_id'] = $order_sell_id;
    	$data['add_time'] = time();
    	$data['status'] = 1;
    	// 		dump($data);
    	$res = M('Trade')->add($data);
    	return $res;
    }

    /**
     * 用户商品持有量
     * @param 用户id $member_id
     * @param 商品id $goods_id
     * @param 商品数量   $num
     * @param 买卖   $type sell/buy
     * @return unknown
     */
    public function addGoodsUser($member_id,$goods_id,$num,$type){
    	$where['member_id'] = $member_id;
    	$where['goods_id'] = $goods_id;
    	$goods_user = M('Goods_member')->where($where)->find();
    	if($type == 'buy'){
    		if($goods_user){
    			$res = M('Goods_member')->where($where)->setInc('num',$num);
    		}else{
    			$data['num'] = $num;
    			$data['member_id'] = $member_id;
    			$data['goods_id'] = $goods_id;
    			$data['status']=0;
    			$res = M('Goods_member')->add($data);
    
    		}
    	}
    	if($type == 'sell'){
    		if($goods_user){
    			$res = M('Goods_member')->where($where)->setDec('num',$num);
    		}
    	}
    	return $res;
    }
    /**
     * 买入记录页面
     */
    public function mairu(){
    	$member_id = $_SESSION['USER_KEY_ID'];
    	//查看自己购买的股票记录
    	$list = M('Trade')->where(array('buy_member'=>$member_id))->select();
    	foreach($list as $k=>$v){
    		$list[$k]['money'] = $list[$k]['price']/$list[$k]['num'];
    	}
    	$this->assign('list',$list);
    	$this->display();
    }
    
    /**
     * 股票拆分页面
     */
    public function chaifen(){
    	
    	$this->display();
    }
	public function selling(){
		$member_id = $_SESSION['USER_KEY_ID'];
		$where['member_id'] = $member_id;
		$where['type'] = 'sell';
		$orders = M('Orders')->where($where)->select();
		foreach($orders as $k=>$v){
			$orders[$k]['all_money'] = $orders[$k]['num']*$orders[$k]['price'];
		}
		$this->assign('orders',$orders);
		$this->display();
	}
	/**
	 * 成交记录页面
	 */
	public function trade_list(){
		//查看自己完成的订单
		$map['member_id'] = $_SESSION['USER_KEY_ID'];
		$map['status'] = 1;
		$count      = M('Orders')->where($map)->count();// 查询满足要求的总记录数
		$Page       = new \Think\Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数(25)
		$show       = $Page->show();// 分页显示输出
		
		
		$list = M('Orders')->where($map)->order('add_time desc')->limit($Page->firstRow.','.$Page->listRows)->select();
		$this->assign('list',$list);
		$this->assign('page',$show);// 赋值分页输出
		$this->display();
	}
	
	
	public function maichu(){
		$this->display();
	}

	
	
	
	
	
	
	
	
	
}